<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { fetchParamSave } from '@/service/api';
import { useLoading } from '~/packages/hooks';

type Model = Api.System.Param.ParamFormModel;

defineOptions({ name: 'ParamFormDrawer' });

interface Props {
  operateType: UI.TableOperateType;
  rowData?: Api.System.Param.ParamRecord | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const { formRef, validate, restoreValidation } = useForm();
const { createRequiredRule } = useFormRules();

function createDefaultModel(): Model {
  return {
    id: '',
    code: '',
    name: '',
    value: '',
    remark: ''
  };
}

const model = ref<Model>(createDefaultModel());

type RuleKey = Extract<Model, 'code' | 'name' | 'enabled'>;
const rules = ref<Record<RuleKey, App.Global.FormRule>>({
  code: createRequiredRule($t('form.required')),
  name: createRequiredRule($t('form.required')),
  value: createRequiredRule($t('form.required')),
  enabled: createRequiredRule($t('form.enabled'))
});

const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: '新增参数',
    edit: '编辑参数'
  };
  return titles[props.operateType];
});

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

const { loading, startLoading, endLoading } = useLoading(false);

async function handleSubmit() {
  try {
    await validate();
    startLoading();
    // request
    const { error } = await fetchParamSave(model.value);
    // success
    if (error) return;
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } finally {
    endLoading();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <ElDrawer v-model="visible" :title="title" :close-on-click-modal="false" direction="rtl" size="450">
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElFormItem label="参数名称" prop="name">
        <ElInput v-model="model.name" placeholder="参数名称" maxlength="200" show-word-limit />
      </ElFormItem>
      <ElFormItem label="参数编码" prop="code">
        <ElInput v-model="model.code" placeholder="参数编码" maxlength="200" show-word-limit />
      </ElFormItem>
      <ElFormItem label="参数值" prop="value">
        <ElInput v-model="model.value" placeholder="参数值" maxlength="200" show-word-limit />
      </ElFormItem>
      <ElFormItem label="备注" prop="remark">
        <ElInput v-model="model.remark" type="textarea" placeholder="备注" maxlength="500" show-word-limit />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElSpace v-loading="loading" :size="16">
        <ElButton @click="closeDrawer">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDrawer>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-input) {
  width: 100% !important;
}
</style>
